/*
 * Copyright 2008 Max Kugland
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.splink.library.logging.logoutput {
	import flash.events.Event;
	import flash.events.IOErrorEvent;
	import flash.events.SecurityErrorEvent;
	import flash.net.XMLSocket;

	import org.splink.library.logging.LogEvent;
	import org.splink.library.logging.LogLevel;	

	/**
	 * Sends log messages to the Powerflasher SocketOutputServer (SOS) 
	 * 
	 * @author Max Kugland
	 */
	public class SosOutput extends LogOutput {
		private var _socket : XMLSocket;
		private var _ip : String;

		public function SosOutput(ip : String = "localhost") {
			_ip = ip;
			connect();
		}

		private function connect() : void {
			_socket = new XMLSocket();
			_socket.addEventListener(Event.CONNECT, onInitialized);
			_socket.addEventListener(IOErrorEvent.IO_ERROR, onError);			_socket.addEventListener(SecurityErrorEvent.SECURITY_ERROR, onError);
			_socket.connect(_ip, 4445);
		}

		private function onError(event : Event) : void {
			_initialized = true;
			//SOS Error. Probably SOS is not running.
		}

		private function onInitialized(e : Event) : void {
			if(_socket.connected) {
				_socket.removeEventListener(Event.CONNECT, onInitialized);
				_socket.send('<clear/>\n');
				_socket.send("<appName>SosOutput</appName>\n");				_socket.send("<identify/>\n");
				
				_socket.send("<setKey><name>FATAL</name><color>" + 0xFFFF00 + "</color></setKey>\n");				_socket.send("<setKey><name>ERROR</name><color>" + 0xFF0000 + "</color></setKey>\n");
				_socket.send("<setKey><name>WARNING</name><color>" + 0xFFFFCC + "</color></setKey>\n");
				_socket.send("<setKey><name>INFO</name><color>" + 0xCCFFFF + "</color></setKey>\n");
				_socket.send("<setKey><name>DEBUG</name><color>" + 0x00FF00 + "</color></setKey>\n");				_socket.send("<setKey><name>TRACE</name><color>" + 0xFFFFFF + "</color></setKey>\n");				_socket.send("<setKey><name>GARBAGE</name><color>" + 0x999900 + "</color></setKey>\n");
				_initialized = true;
			}
		}

		/**
		 * @inheritDoc
		 */
		override public function log(event : LogEvent) : void {
			if(_socket.connected && _initialized)
				_socket.send(buildMessage(LogLevel.getLevelOutputName(event.getLevel()), _formatter.format(event)));
		}

		private function buildMessage(level : String, msg : String) : String {
			return '<showMessage key="' + level + '"/> ' + msg + " \n";
		}
	}
}
